<!--
	作者：offline
	时间：2019-11-07
	描述：实物对账明细报表
-->
<template>
	<div class="m-view-goodsAccountReport m-window">
		<div class="m-condition">
			<el-row :gutter="10">
				<el-form ref="ruleForm" label-width="70px" :inline-message="true" label-position="left">
					<el-col :span="accountType==4?7:7">
						<el-form-item :label="label" class="rightItem">
							<el-select
								value-key="id"
								v-model="searchForm.companyCode"
								:placeholder="`请选择${label}`"
								@change="companyChange"
								ref="content"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item.companyCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="6">
						<el-form-item label="申请日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.createSt"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								:clearable="false"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-date-picker
							v-model="searchForm.createEt"
							:clearable="false"
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
						></el-date-picker>
					</el-col>
					<el-col :span="6">
						<el-form-item label="对账单号">
							<el-input v-model="searchForm.gooAccNo" placeholder="请输入对账单号" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
			<el-row :gutter="10">
				<el-form label-width="70px" :inline-message="true" label-position="left">
					<el-col :span="7" v-if="accountType==1">
						<el-form-item label="供应商" class="rightItem">
							<el-input
								placeholder="请选择供应商"
								v-model="searchForm.supplierName"
								clearable
								@focus="showSupplierDialog"
								readonly
								@mouseenter.native="mouseEnter"
								@mouseleave.native="mounseLeave"
							>
								<el-button slot="append" icon="el-icon-search" @click="showSupplierDialog"></el-button>
								<span slot="suffix" @click="inputClearSon" class="m-cleanInput" v-show="inputClearBut">
									<i class="el-input_icon el-icon-circle-close el-input__clear"></i>
								</span>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="入库日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.postSt"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								:clearable="false"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-date-picker
							v-model="searchForm.postEt"
							:clearable="false"
							placeholder="结束月"
							value-format="yyyy-MM-dd"
						></el-date-picker>
					</el-col>
					<el-col :span="4">
						<el-form-item label="订单号">
							<el-input v-model="searchForm.purOrdNo" placeholder="请输入订单号" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-form>
				<el-col :span="2">
					<el-button type="primary" @click="searchReport(1)">查询</el-button>
				</el-col>
			</el-row>
		</div>
		<!--实物对账明细列表-->
		<div class="m-agTable m-bottom m-top2">
			<agGridComponents
				ref="reportGrid"
				:isColFit="isColFit"
				:getGridOptions="reportGridOptions"
				:getColumnDefs="reportColumnDefs"
			></agGridComponents>
		</div>
		<!-- 分页组件 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageInfo.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>
		<!-- 供应商弹窗 -->
		<el-dialog
			title="供应商信息"
			:visible.sync="srmSupplierDialogVisible"
			width="50%"
			:before-close="srmSupplierDialogClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<srmSupplierInfo ref="srmSupplierInfo" :layout="layout" @setSrmSupplierInfo="setSrmSupplierInfo"></srmSupplierInfo>
		</el-dialog>
	</div>
</template>

<script>
import _Api from "@/api"
import constant from "@/public/constant"
import localeText from "@/i18n/agGridText";
import authInfo from "@/public/authInfo"
import Msg from "@/public/message"
import srmSupplierInfo from "@/components/srmSupplierInfo"
import agGridComponents from "@/components/agGridComponents"
import serviceTime from "@/public/serverTime"
import addOperation from "@/public/addOperation"

export default {
	props:{
		setClickValue: '',
	},
	data () {
		return {
			inputClearBut: false,
			label: '',
			// 查询条件  
			searchForm: {
				companyCode: '',
				gooAccNo: '',
				purOrdNo: '',
				createSt: '',
				createEt: '',
				postSt: '',
				postEt: ''
			},
			rowData: [],
			//表格是否自适应窗口宽度
			isColFit: true,
			//是否显示选择供应商弹窗
			srmSupplierDialogVisible: false,
			layout: {},
			comOptions: [],
			// 分页信息
			pageInfo: {
				current: 1,
				size: 30,
				total: 0
			},
			//   账户类型
			accountType: '',
			// 底部合计栏数据
			totalAmount: {
				unitMoney: 0,
				adjustMoney: 0,
				sumMoney: 0
			}
		}
	},
	beforeMount () {
		this.reportGridOptions = {
			context: { componentParent: this },
			animateRows: true, //排序动画
			enableFilter: true, //列过滤器
			enableSorting: true, //列排序
			enableCellChangeFlash: true,
			enableRangeSelection: true,
			enableColResize: true,
			localeText: localeText,
			pinnedBottomRowData: this.createData(1, 'Bottom'),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { 'color': 'red', 'font-weight': "bold" }
				}
				if (params.data.isMsExist == "1") {
					return { 'color': 'red' }
				}
			},
		}

		//   汇总报表-表格列信息
		this.reportColumnDefs = [
			{ headerName: "实物对账单号", field: "gooAccNo", width: 160 },
			{
				headerName: "申请日期",
				field: "createDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value && params.value != "")
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{
				headerName: "对账类型",
				field: "type",
				width: 100,
				cellRenderer: function (params) {
					if (params.value == "1")
						return '<span class="ag-icon">费用类</span>'
					else if (params.value == "0")
						return '<span class="ag-icon">材料类</span>'
				},
			},
			{ headerName: "公司", field: "companyCode", width: 70 },
			{ headerName: "公司名称", field: "companyName", width: 180 },
			{ headerName: "供应商", field: "supplierCode", width: 100 },
			{ headerName: "供应商名称", field: "supplierName", width: 180 },
			{ headerName: "采购订单号", field: "purOrdNo", width: 120 },
			{ headerName: "订单行", field: "purOrdMxNo", width: 100 },
			{
				headerName: "订单日期",
				field: "purOrdDate",
				width: 120,
				cellRenderer: function (params) {
					if (params.value && params.value != "")
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
			},
			{ headerName: "物料编号", field: "matCode", width: 100 },
			{ headerName: "物料描述", field: "matName", width: 130 },
			{
				headerName: "入库日期",
				field: "postDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value && params.value != "" && !params.node.rowPinned) {
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
					} else {
						return params.value
					}

				}
			},
			{ headerName: "订单数量", field: "orderAmount", width: 100 },
			{ headerName: "入库数量", field: "amount", width: 100 },
			{ headerName: "订单单位", field: "unitCode", width: 100 },
			{ headerName: "价格数量", field: "priceAmount", width: 100 },
			{ headerName: "价格单位", field: "priceUnit", width: 100 },
			{ headerName: "含税单价", field: "unitPrice", width: 100 },
			{ headerName: "含税金额", field: "unitMoney", width: 100 },
			{ headerName: "差异金额", field: "adjustMoney", width: 100 },
			{
				headerName: "金额合计",
				field: "sumMoney",
				width: 100,
				cellRenderer: function (params) {
					if (params.value && params.value != "")
						return params.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
					else
						return 0
				}
			}
		]
	},
	mounted () {
		/*
		 * accountType
		 * 1为内部用户
		 * 4为供应商账户
		 */
		this.accountType = constant.accountType;
		if (this.accountType == 4) {
			const { supplierCode, supplierName } = constant.supplierData;
			this.searchForm.supplierCode = supplierCode
			this.searchForm.supplierName = supplierName
			this.label = '客户'
		} else {
			this.label = '公司'
		}
		this.initDate(this.searchType)
	},
	components: {
		srmSupplierInfo,
		agGridComponents
	},
	methods: {
		// 查询实物对账报表数据
		searchReport (flag) {
			let validat = this.validatQuery(this.searchForm, this.searchType)
			if (flag) this.pageInfo.current = 1
			const { current, size } = this.pageInfo
			if (!validat) return
			let params = {
				...this.searchForm,
				current,
				size
			}
			this.$refs.reportGrid.loading = true
			// 获取报表数据   
			_Api.getGoodsAccountDetailReport(params).then(({ data }) => {
				this.$refs.reportGrid.loading = false
				if (data.code === 1) {
					this.rowData = data.rows
					this.pageInfo.total = data.total
					this.rowData.forEach(row => {
						if (!row.unitMoney) row.unitMoney = 0
						// 计算底部合计数据
						this.totalAmount.unitMoney = addOperation.accAdd(row.unitMoney, this.totalAmount.unitMoney)
						this.totalAmount.adjustMoney = addOperation.accAdd(row.adjustMoney, this.totalAmount.adjustMoney)
						this.totalAmount.sumMoney = addOperation.accAdd(row.sumMoney, this.totalAmount.sumMoney)
					})
					this.$refs.reportGrid.gridOptions.api.setRowData(this.rowData)
					this.$refs.reportGrid.gridOptions.api.setPinnedBottomRowData(
						this.createData(1, "Bottom")
					)
				} else {
					Msg.showErrorMsg(data.info)
				}
			})
				.catch(err => {
					this.$refs.reportGrid.loading = false
					Msg.showErrorMsg(err.data.message)
				})
		},
		//后面加的，根据单号查询实物信息
		getList(val){
			this.$refs.reportGrid.loading = true;
			this.pageInfo.current = 1;
			const { current, size } = this.pageInfo
			let params = {
				gooAccNo: val.no,
				current,
				size
			}
			// 获取报表数据   
			_Api.getGoodsAccountDetailReport(params).then(({ data }) => {
				this.$refs.reportGrid.loading = false
				if (data.code === 1) {
					this.rowData = data.rows
					this.pageInfo.total = data.total
					this.rowData.forEach(row => {
						if (!row.unitMoney) row.unitMoney = 0
						// 计算底部合计数据
						this.totalAmount.unitMoney = addOperation.accAdd(row.unitMoney, this.totalAmount.unitMoney)
						this.totalAmount.adjustMoney = addOperation.accAdd(row.adjustMoney, this.totalAmount.adjustMoney)
						this.totalAmount.sumMoney = addOperation.accAdd(row.sumMoney, this.totalAmount.sumMoney)
					})
					this.$refs.reportGrid.gridOptions.api.setRowData(this.rowData)
					this.$refs.reportGrid.gridOptions.api.setPinnedBottomRowData(
						this.createData(1, "Bottom")
					)
				} else {
					Msg.showErrorMsg(data.info)
				}
			})
			.catch(err => {
				this.$refs.reportGrid.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		//  验证查询参数
		validatQuery (params, type) {
			const {
				companyCode, //公司编码
				createSt, //申请开始日期
				createEt,  //申请结束日期
				postSt,  //入库开始日期
				postEt  //入库结束日期
			} = params
			if (!companyCode) {
				Msg.showPopMsg(`请选择${this.label}`)
				return false
			} else if (new Date(createSt).getTime() - new Date(createEt).getTime() > 0) {
				Msg.showPopMsg('开始日期不能大于结束日期!')
				return false
			} else if (new Date(postSt).getTime() - new Date(postEt).getTime() > 0) {
				Msg.showPopMsg('入库开始日期不能大于入库结束日期!')
				return false
			}
			return true
		},
		// 选择公司回调
		companyChange (val) {
			if (this.accountType == 1) {
				this.layout.companyCode = val
				this.layout.auth = true
				this.searchForm.supplierCode = ""
				this.searchForm.supplierName = ""
			}
		},
		// 输入框清除事件监听
		inputClearSon () {
			this.searchForm.supplierName = ""
			this.searchForm.supplierCode = ""
			this.inputClearBut = false
		},
		// 回显选择的供应商信息
		setSrmSupplierInfo (msg) {
			if (msg.length > 0) {
				const { supplierCode, supplierName } = msg[0]
				this.srmSupplierDialogVisible = false
				this.searchForm.supplierCode = supplierCode
				this.searchForm.supplierName = supplierName
			}
		},
		// 打开供应商弹窗
		showSupplierDialog () {
			let that = this;
			if (!this.layout.companyCode) {
				this.$alert(`提示：请选择${this.label}！`, {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				this.$refs.content.focus()
				return
			} else {
				this.srmSupplierDialogVisible = true
				this.$nextTick(_ => {
					that.$refs.srmSupplierInfo.search()
				})
			}
		},
		// 关闭供应商弹窗回调
		srmSupplierDialogClose (done) {
			this.$refs.srmSupplierInfo.keyWord = ""
			this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
				this.$refs.srmSupplierInfo.keyWord
			)
			done()
		},
		// 关闭条码信息弹窗
		historyDialogClose () {
			this.historyVisible = false
		},
		// 供应商输入框鼠标移入事件监听
		mouseEnter () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = true
		},
		// 供应商输入框鼠标移出事件监听
		mounseLeave () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = false
		},
		// 每页条数改变回调
		handleSizeChange (size) {
			this.pageInfo.size = size
			this.pageInfo.current = 1
			this.searchReport()
		},
		// 页码改变回调
		handleCurrentChange (current) {
			this.pageInfo.current = current
			this.searchReport()
		},
		// 点击上一页回调
		handlePrevClick (current) {
			this.pageInfo.current = current
		},
		// 点击下一页回调
		handleNextClick (current) {
			this.pageInfo.current = current
		},
		// 根据账户类型获取公司下拉列表
		getCompanyOption () {
			authInfo.getAuthInfo().then(data => {
				this.comOptions = data
				this.searchForm.companyCode = data[0].companyCode
				this.searchForm.companyName = data[0].companyName
				this.layout.companyCode = data[0].companyCode
				this.layout.auth = true
				if (this.accountType == 1) {
					//后面加的,用来查询从会计明细报表跳转过来查询单号的信息
					if(this.setClickValue && this.setClickValue != ""){
						this.getList(this.setClickValue);
						return
					}
					this.searchReport(1)
				}
			})
				.catch(err => {
					//后面加的,用来查询从会计明细报表跳转过来查询单号的信息
					if(this.setClickValue && this.setClickValue != ""){
						this.getList(this.setClickValue);
						return
					}
					Msg.showErrorMsg(err)
				});
		},
		// 初始化查询时间
		initDate () {
			// 日期范围默认30天内
			serviceTime.getServiceTime().then((serviceTime) => {
				let startDate = new Date(serviceTime.getTime() - 3600 * 1000 * 24 * 30 * 3).Format('yyyy-MM-dd')
				let endDate = serviceTime.Format("yyyy-MM-dd")
				this.searchForm.createSt = startDate
				this.searchForm.createEt = endDate
				this.getCompanyOption()
			}).catch(err => {
				Msg.showErrorMsg(err)
			})
		},
		// 创建底部合计栏
		createData (count, prefix) {
			let result = []
			for (let i = 0; i < count; i++) {
				const { unitMoney, adjustMoney, sumMoney } = this.totalAmount
				result.push({
					postDate: "合计",
					unitMoney,
					adjustMoney,
					sumMoney
				})
			}
			return result;
		},
	},
}
</script>

<style lang="less">
.m-view-goodsAccountReport {
	.el-form {
		.el-form-item {
			margin-bottom: 0;
		}
	}
}
</style>